% inputs:
% pooledData is the table of identifiers, etc
% numRepeats is how many bootstrap distributions to generate
% IDcolumns specifies which columnds to use as the identifiers for the
% heirarchical bootstrap


function idx = nestedBootstrapNVCsample_v2_0(pooledData,numRepeats,IDcolumns)

if nargin < 2 || isempty(numRepeats)
    numRepeats = 10000;
end

[uniqueMice,~,mouseID] = unique(pooledData(:,IDcolumns(1)));
nummice = size(uniqueMice,1);
mice = cell(1,nummice);
for n = 1:length(mice)
    %find unique mice
    i1 = mouseID == n;
    [uid,~,ic] = unique(pooledData(i1,IDcolumns(2)));
    mice{n} = cell(2,size(uid,1));
    %within unique mice, find unique stimIDs
    for n2 = 1:size(uid,1)
        mice{n}{1,n2} = uid{n2,1};            %stores the identity of the repeat
        mice{n}{2,n2} = find(pooledData{:,IDcolumns(2)} == uid{n2,1});
    end
end

idx = [];
for n = 1:numRepeats
    i1 = randi(nummice,nummice,1);
    mouseidx = [];
    for n2 = 1:length(i1)
        curidx = [];
        numroi = size(mice{i1(n2)},2);
        i2 = randi(numroi,numroi,1);
        for n3 = 1:length(i2)
            numsamples = size(mice{i1(n2)}{2,i2(n3)},1);
            try
            i3 = randi(numsamples,numsamples,1);
            catch
                'g'
            end
            temp = mice{i1(n2)}{2,i2(n3)};
            curidx = [curidx;temp(i3)];
        end
        mouseidx = nancat(mouseidx,curidx,2);
    end
    idx = nancat(idx,mouseidx,3);
end
idx = idx(:,:,2:end);
